import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/storage_service.dart';
import 'package:vista/shared/services/relation_bond.dart';
import 'package:vista/shared/services/dialog_lens.dart';
import 'package:vista/shared/services/post_studio.dart';
import 'package:vista/shared/services/circle_gallery.dart';
import 'package:vista/shared/services/theme_challenge_service.dart';
import 'package:vista/shared/services/tutorial_video_service.dart';
import 'package:vista/shared/services/daily_inspiration_service.dart';
import 'package:vista/shared/utils/widget_extension.dart';

/// 启动页
/// 负责初始化应用数据和显示启动画面
class SplashView extends StatefulWidget {
  const SplashView({super.key});

  @override
  State<SplashView> createState() => _SplashViewState();
}

class _SplashViewState extends State<SplashView> {
  @override
  void initState() {
    super.initState();
    _initializeApp();
  }

  /// 初始化应用
  Future<void> _initializeApp() async {
    try {
      // 记录开始时间
      final startTime = DateTime.now();

      // 初始化存储服务
      final storageService = getIt.get<StorageService>();
      await storageService.clearAll();
      await storageService.initialize();

      // 初始化默认用户数据
      final authFocus = getIt.get<AuthFocus>();
      await authFocus.initializeDefaultUsers();

      // 初始化默认关注关系
      final relationBond = getIt.get<RelationBond>();
      await relationBond.initializeDefaultRelations();

      // 初始化默认聊天数据
      final dialogLens = getIt.get<DialogLens>();
      await dialogLens.initializeDefaultChats();

      // 初始化默认动态数据
      final postStudio = getIt.get<PostStudio>();
      await postStudio.initializeDefaultPosts();

      // 初始化默认圈子数据
      final circleGallery = getIt.get<CircleGallery>();
      await circleGallery.initializeDefaultGroups();

      // 初始化默认主题挑战数据
      final themeChallengeService = getIt.get<ThemeChallengeService>();
      await themeChallengeService.initializeDefaultChallenges();

      // 初始化默认教程视频数据
      final tutorialVideoService = getIt.get<TutorialVideoService>();
      await tutorialVideoService.initializeDefaultVideos();

      // 初始化默认每日灵感数据
      final dailyInspirationService = getIt.get<DailyInspirationService>();
      await dailyInspirationService.initializeDefaultInspirations();

      // 计算已用时间，确保至少停留2秒
      final elapsed = DateTime.now().difference(startTime);
      const minDuration = Duration(seconds: 2);
      if (elapsed < minDuration) {
        await Future.delayed(minDuration - elapsed);
      }

      // 直接跳转到主页（导航中心）
      if (mounted) {
        getIt<NavigationService>().pushNamedAndRemoveUntil(
          Routes.main,
          predicate: (route) => false,
        );
      }
    } catch (e) {
      // 如果初始化失败，仍然跳转到主页
      if (mounted) {
        // 确保至少停留2秒
        await Future.delayed(const Duration(seconds: 2));
        getIt<NavigationService>().pushNamedAndRemoveUntil(
          Routes.main,
          predicate: (route) => false,
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my-background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: Center(
          child: [
                // Logo
                ClipRRect(
                  borderRadius: BorderRadius.circular(12.r),
                  child: Image.asset(
                    'assets/images/logo.png',
                    width: 80.w,
                    height: 80.w,
                  ),
                ),
                SizedBox(height: 10.h),
                // 项目名称
                Text(
                  'Vista',
                  style: GoogleFonts.alegreyaSans(
                    fontSize: 24.sp,
                    fontWeight: FontWeight.w800,
                    color: Colors.white,
                    letterSpacing: 2,
                  ),
                ),
                SizedBox(height: 200.h),
              ]
              .verticalShot(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
              )
              .frameAll(24.w),
        ),
      ),
    );
  }
}
